package com.lanyou.esb.service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.lanyou.cook.common.Constants;
import com.lanyou.esb.repository.IfReqQuantityRepository;
import com.lanyou.esb.vo.QuantityDetailVo;
import com.lanyou.esb.web.param.QuantityControlParam;

/**
 * 流量明细服务<br>
 * 
 * 
 * @author Davey.wu
 */
@Service
public class QuantityDetailService {
	@PersistenceContext
	private EntityManager entityManager;
	@Autowired
	private IfReqQuantityRepository interfaceRequestQuantityRepository;
	/** 时间格式：yyyy-MM-dd HH:mm:ss **/
	private static FastDateFormat FASTDATEFORMAT_YYYYMMDDHHMMSS = FastDateFormat
			.getInstance(Constants.DATETIME_PATTERN_1);

	/**
	 * 获取月流量明细信息
	 * 
	 * @param param
	 *            ：查询条件
	 * @param pageable
	 *            ：分页对象
	 * @param sysIds
	 * @return
	 * @throws ParseException
	 */
	public QuantityDetailVo findQuantityDetailByMonth(
			QuantityControlParam param, Pageable pageable, List<String> sysIds)
			throws ParseException {
		if(sysIds==null||sysIds.isEmpty()){
			QuantityDetailVo vo = new QuantityDetailVo();
			vo.setTotal(0l);
			vo.setEntrys(new ArrayList<>(0));
			return vo;
		}
		String date = "";
		if (StringUtils.isNotBlank(param.getDate())) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(FASTDATEFORMAT_YYYYMMDDHHMMSS.parse(param
					.getDate()));
			// 设置日期为每月的第一天
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			calendar.set(Calendar.HOUR_OF_DAY, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			date = FASTDATEFORMAT_YYYYMMDDHHMMSS.format(calendar);
		}
		QuantityDetailVo vo = new QuantityDetailVo();
		// 获取总记录数
		BigInteger total = getTotal(param, date, sysIds);
		// 无记录，返回空集
		if (total == null || total.longValue() <= 0) {
			vo.setTotal(0l);
			vo.setEntrys(new ArrayList<>(0));
			return vo;
		}
		// 获取数据
		List<Object[]> objects = findQuantityDetailReport(
				pageable.getPageNumber() * pageable.getPageSize(),
				pageable.getPageSize(), param, date, sysIds);
		// 设置总记录数
		vo.setTotal(total.longValue());
		List<QuantityDetailVo.Entry> entrys = new ArrayList<>(objects.size());
		vo.setEntrys(entrys);
		// 转换结果集
		for (Object[] object : objects) {
			String fieldName = object[0] != null ? (String) object[0] : "";
			String systemName = object[1] != null ? (String) object[1] : "";
			String ifName = object[2] != null ? (String) object[2] : "";
			String status = object[3] != null ? (String) object[2] : "";
			int times = object[4] != null ? ((BigDecimal) object[4]).intValue()
					: 0;

			QuantityDetailVo.Entry entry = QuantityDetailVo.Entry.getInstance(
					fieldName, systemName, ifName, status, times);
			entrys.add(entry);
		}
		return vo;
	}

	/**
	 * 获取流量明细
	 * 
	 * @param pageNumber
	 *            :页码
	 * @param pageSize
	 *            ：页大小
	 * @param param
	 *            ：查询条件
	 * @param date
	 *            ：日期
	 * @return
	 */
	private List<Object[]> findQuantityDetailReport(long pageNumber,
			long pageSize, QuantityControlParam param, String date,
			List<String> sysIds) {
		String sql = "SELECT  "
				+ "(SELECT F.FIELD_NAME FROM t_cook_db_field F WHERE F.FIELD_ID=V0.FIELD_ID) AS fieldName, "
				+ "(SELECT S.SYSTEM_NAME FROM t_cook_bu_field_system S WHERE S.FIELD_SYSTEM_ID=V0.FIELD_SYSTEM_ID) AS systemName, "
				+ "V0.IF_NAME, "
				+ "(SELECT H.IF_STATUS FROM t_esb_bu_if_http H WHERE H.IF_HTTP_ID=V0.IF_ID) AS ifStatus, "
				+ "V0.times "
				+ " FROM  "
				+ "(SELECT  t.FIELD_ID,t.FIELD_SYSTEM_ID,t.IF_ID,t.IF_NAME,SUM(t.ACC_TIME) AS times FROM T_ESB_BU_IF_ACC_TIMES t "
				+ "WHERE  t.field_system_id in(:sysIds) and  EXISTS(SELECT H.IF_HTTP_ID FROM t_esb_bu_if_http H WHERE H.IF_HTTP_ID=t.IF_ID AND H.IS_ENABLE='1') ";
		// 添加接口名称条件
		if (StringUtils.isNotBlank(param.getIfName())) {
			sql += "AND t.IF_NAME LIKE :ifName ";
		}
		// 添加领域条件
		if (StringUtils.isNotBlank(param.getFieldId())) {
			sql += "AND t.FIELD_ID =:fieldId ";
		}
		// 添加系统条件
		if (StringUtils.isNotBlank(param.getSystemId())) {
			sql += "AND t.FIELD_SYSTEM_ID =:systemId ";
		}
		// 添加日期条件
		if (StringUtils.isNotBlank(date)) {
			sql += "AND t.STATISTICS_DATE=:targetDate ";
		}

		sql += " GROUP BY t.IF_ID LIMIT :pageNumber,:pageSize) AS V0  ";
		Query query = entityManager.createNativeQuery(sql);
		// 用户管理的系统
		query.setParameter("sysIds", sysIds);
		// 设置领域参数
		if (StringUtils.isNotBlank(param.getFieldId())) {
			query.setParameter("fieldId", param.getFieldId());
		}
		// 设置系统参数
		if (StringUtils.isNotBlank(param.getSystemId())) {
			query.setParameter("systemId", param.getSystemId());
		}
		// 设置接口名称参数
		if (StringUtils.isNotBlank(param.getIfName())) {
			query.setParameter("ifName", param.getIfName());
		}
		// 设置日期参数
		if (StringUtils.isNotBlank(date)) {
			query.setParameter("targetDate", date);
		}
		query.setParameter("pageNumber", pageNumber);
		query.setParameter("pageSize", pageSize);
		// 获取查询结果
		List<Object[]> rows = query.getResultList();
		return rows;
	}

	/**
	 * 获取总记录数
	 * 
	 * @param param
	 *            :查询条件
	 * @param date
	 *            ：日期
	 * @return
	 */
	private BigInteger getTotal(QuantityControlParam param, String date,
			List<String> sysIds) {
		String sql = "SELECT COUNT(V0.IF_ID) AS total FROM(SELECT t.IF_ID FROM T_ESB_BU_IF_ACC_TIMES t "
				+ "WHERE t.field_system_id in(:sysIds) and EXISTS(SELECT H.IF_HTTP_ID FROM t_esb_bu_if_http H WHERE H.IF_HTTP_ID=t.IF_ID AND H.IS_ENABLE='1') ";
		// 添加接口名称条件
		if (StringUtils.isNotBlank(param.getIfName())) {
			sql += "AND t.IF_NAME LIKE :ifName ";
		}
		// 添加领域条件
		if (StringUtils.isNotBlank(param.getFieldId())) {
			sql += "AND t.FIELD_ID =:fieldId ";
		}
		// 添加系统条件
		if (StringUtils.isNotBlank(param.getSystemId())) {
			sql += "AND t.FIELD_SYSTEM_ID =:systemId ";
		}
		// 添加日期条件
		if (StringUtils.isNotBlank(date)) {
			sql += "AND t.STATISTICS_DATE=:targetDate ";
		}
		sql += "GROUP BY t.IF_ID) AS V0 ";
		Query query = entityManager.createNativeQuery(sql);
		// 用户管理的系统
		query.setParameter("sysIds", sysIds);
		// 设置领域参数
		if (StringUtils.isNotBlank(param.getFieldId())) {
			query.setParameter("fieldId", param.getFieldId());
		}
		// 设置系统参数
		if (StringUtils.isNotBlank(param.getSystemId())) {
			query.setParameter("systemId", param.getSystemId());
		}
		// 设置接口名称参数
		if (StringUtils.isNotBlank(param.getIfName())) {
			query.setParameter("ifName", param.getIfName());
		}
		// 设置日期参数
		if (StringUtils.isNotBlank(date)) {
			query.setParameter("targetDate", date);
		}
		// 获取查询结果
		List rows = query.getResultList();
		// 无记录，返回0
		if (rows == null || rows.isEmpty()) {
			return new BigInteger("0");
		}
		BigInteger total = (BigInteger) rows.get(0);
		return (BigInteger) total;
	}

}
